﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SnongPhoneShop.Models;
using System.IO;

namespace SnongPhoneShop.Controllers
{
    public class AdminController : Controller
    {
        SnongPhoneShopEntities db = new SnongPhoneShopEntities();
        StoredProcedure sp = new StoredProcedure();

        public ActionResult Index()
        {
            if (Session["Admin"] != null) return View(db);
            else return RedirectToAction("Dang_Nhap");
        }
        #region [Đăng nhập]
        public ActionResult Dang_Nhap()
        {

            if (Session["Admin"] == null) return View();
            else return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Dang_Nhap(FormCollection Fc)
        {
            string ID = Fc["txtID"];
            string PW = Fc["txtPW"];
            var Admin = db.QuanTris.FirstOrDefault(m => m.TenDangNhap.Equals(ID) && m.MatKhau.Equals(PW));
            if (Admin != null)
            {
                Session.Add("Admin", ID);
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.Message = "Sai tên đăng nhập hoặc mật khẩu!";
                return View();
            }
        }
        #endregion
        #region [Đăng xuất]
        public ActionResult Dang_Xuat()
        {
            if (Session["Admin"] != null)
            {
                Session.Remove("Admin");
            }
            return RedirectToAction("Index");
        }
        #endregion
        #region Quản lí sản phẩm
        public ActionResult QL_SanPham()
        {
            if (Session["Admin"] != null)
            {
                var L = sp.GetListProduct();
                return View(L);
            }
            return RedirectToAction("Dang_Nhap");
        }
        public ActionResult ReversePublishProduct(string id)
        {
            sp.ReversePublishStatusOfProductByID(id);
            return RedirectToAction("QL_SanPham");
        }
        public ActionResult ReverseFeatureProduct(string id)
        {
            sp.ReverseFeatureStatusOfProductByID(id);
            return RedirectToAction("QL_SanPham");
        }
        public void SetListPublishStatus(string list, bool status)
        {
            sp.SetPublishStatusOfListProduct(list, status);
        }
        public void SetListFeatureStatus(string list, bool status)
        {
            sp.SetFeatureStatusOfListProduct(list, status);
        }
        public void DeleteProduct(string id)
        {
            sp.DeleteProductByID(id);
        }
        public void DeleteListProduct(string list)
        {
            sp.DeleteListProduct(list);
        }

        [HttpGet]
        public ActionResult SuaSP(string id)
        {
            var sp = db.SanPhams.FirstOrDefault(m => m.MaSanPham.TrimEnd() == id);
            ViewBag.ListPublish = new SelectList(new List<bool> { true, false });
            ViewBag.ListNoiBat = new SelectList(new List<bool> { true, false });
            ViewBag.ListTinhTrang = new SelectList(db.TinhTrangs.ToList(), "MaTinhTrang", "TenTinhTrang");
            ViewBag.ListPhatHanh = new SelectList(db.TrangThaiPhatHanhs.ToList(), "MaTrangThai", "TenTrangThai");
            ViewBag.ListKieuManHinh = new SelectList(db.KieuManHinhs.ToList(), "MaKieuManHinh", "TenKieuManHinh");
            ViewBag.ListCamUng = new SelectList(db.CamUngs.ToList(), "MaCamUng", "TenCamUng");
            ViewBag.ListKieuDang = new SelectList(db.KieuDangs.ToList(), "MaKieuDang", "TenKieuDang");
            ViewBag.ListBanPhim = new SelectList(db.LoaiBanPhims.ToList(), "MaLoaiBanPhim", "TenLoaiBanPhim");
            ViewBag.ListDM = new SelectList(db.DanhMucSanPhams.ToList(), "MaDanhMuc", "TenDanhMuc");
            return View(sp);
        }
//         [HttpPost]
//         public ActionResult SuaSP(string id, SanPham p, HttpPostedFileBase Files)
//         {
//             sp.UpdateProductByID(id, p);
//             if (Files != null)
//             {
//                 var Filename = Path.GetFileName(Files.FileName);
//                 string newname = (p.MaSanPham.ToString());
//                 string loaisp = sp.getDMSPbyId(int.Parse(p.MaDanhMuc.ToString())).LoaiDanhMuc.TenLoaiDanhMuc;
//                 string hang = sp.getDMSPbyId(int.Parse(p.MaDanhMuc.ToString())).Folder;
//                 if (loaisp == "Điện thoại") loaisp = "DienThoai";
//                 else loaisp = "PhuKien";
//                 var path = Path.Combine(Server.MapPath("~/Images/" + loaisp + "/" + hang), newname + ".jpg");
//                 Files.SaveAs(path);
//                 p.AnhDaiDien = "/Images/" + loaisp + "/" + hang + "/" + newname + ".jpg";
//             }
//             sp.UpdateProductByID(p.MaSanPham, p);
//             return RedirectToAction("QLSanpham");
//         }
        [HttpGet]
        public ActionResult ThemSP()
        {
            ViewBag.ListPublish = new SelectList(new List<bool> { true, false });
            ViewBag.ListNoiBat = new SelectList(new List<bool> { true, false });
            ViewBag.ListTinhTrang = new SelectList(db.TinhTrangs.ToList(), "MaTinhTrang", "TenTinhTrang");
            ViewBag.ListPhatHanh = new SelectList(db.TrangThaiPhatHanhs.ToList(), "MaTrangThai", "TenTrangThai");
            ViewBag.ListKieuManHinh = new SelectList(db.KieuManHinhs.ToList(), "MaKieuManHinh", "TenKieuManHinh");
            ViewBag.ListCamUng = new SelectList(db.CamUngs.ToList(), "MaCamUng", "TenCamUng");
            ViewBag.ListKieuDang = new SelectList(db.KieuDangs.ToList(), "MaKieuDang", "TenKieuDang");
            ViewBag.ListBanPhim = new SelectList(db.LoaiBanPhims.ToList(), "MaLoaiBanPhim", "TenLoaiBanPhim");
            ViewBag.ListDM = new SelectList(db.DanhMucSanPhams.ToList(), "MaDanhMuc", "TenDanhMuc");
            return View();
        }
        [HttpPost]
        public ActionResult ThemSP(FormCollection Fc, HttpPostedFileBase Files)
        {
            SanPham spadd = new SanPham();
            //Danh sach du lieu them moi
            spadd.MaSanPham = Fc["MaSanPham"].ToString();
            spadd.TenSanPham = Fc["TenSanPham"].ToString();
            spadd.DonGia = int.Parse(Fc["Dongia"].ToString());
            spadd.GhiChu = Fc["GhiChu"].ToString();
            spadd.Publish = bool.Parse(Fc["Publish"].ToString());
            spadd.SPNoiBat = bool.Parse(Fc["SPNoiBat"].ToString());
            spadd.MoTa = Fc["MoTa"].ToString();
            spadd.MauSac = Fc["MauSac"].ToString();
            spadd.MaTinhTrang = int.Parse(Fc["MaTinhTrang"].ToString());
            spadd.BaoHanh = Fc["BaoHanh"].ToString();
            spadd.TinhNangNoiBat = Fc["TinhNangNoiBat"].ToString();
            spadd.MaTrangThaiPhatHanh = int.Parse(Fc["MaTrangThaiPhatHanh"].ToString());
            spadd.NgayPhatHanh = DateTime.Parse(Fc["NgayPhatHanh"].ToString());
            spadd.BangTan = Fc["BangTan"].ToString();
            spadd.ChieuDai = float.Parse(Fc["ChieuDai"].ToString());
            spadd.ChieuRong = float.Parse(Fc["ChieuRong"].ToString());
            spadd.ChieuCao = float.Parse(Fc["ChieuCao"].ToString());
            spadd.TrongLuong = float.Parse(Fc["TrongLuong"].ToString());
            spadd.MaKieuManHinh = int.Parse(Fc["MaKieuManHinh"].ToString());
            spadd.KichThuocManHinh = Fc["KichThuocManHinh"].ToString();
            spadd.DoPhanGiai = Fc["DoPhanGiai"].ToString();
            spadd.MaCamUng = int.Parse(Fc["MaCamUng"].ToString());
            spadd.TinhNangKhac = Fc["TinhNangKhac"].ToString();
            spadd.AmBao = Fc["AmBao"].ToString();
            spadd.JackAudio = bool.Parse(Fc["JackAudio"].ToString());
            spadd.LoaNgoai = bool.Parse(Fc["LoaNgoai"].ToString());
            spadd.DanhBaLuuTru = Fc["DanhBaLuuTru"].ToString();
            spadd.BoNhoTrong = Fc["BoNhoTrong"].ToString();
            spadd.HoTroTheNho = Fc["HoTroThenho"].ToString();
            spadd.GPRS = bool.Parse(Fc["GPRS"].ToString());
            spadd.EDGE = bool.Parse(Fc["EDGE"].ToString());
            spadd.C3G = bool.Parse(Fc["C3G"].ToString());
            spadd.MaDanhMuc = int.Parse(Fc["MaDanhMuc"].ToString());

            //update databaseq
            db.SanPhams.Add(spadd);
            db.SaveChanges();
            if (Files.ContentLength > 0)
            {
                var Filename = Path.GetFileName(Files.FileName);
                string newname = (spadd.MaSanPham.ToString());
                string loaisp = sp.getDMSPbyId(int.Parse(spadd.MaDanhMuc.ToString())).LoaiDanhMuc.TenLoaiDanhMuc;
                string hang = sp.getDMSPbyId(int.Parse(spadd.MaDanhMuc.ToString())).Folder;
                if (loaisp == "Điện thoại") loaisp = "DienThoai";
                else loaisp = "PhuKien";
                var path = Path.Combine(Server.MapPath("~/Images/" + loaisp + "/" + hang), newname + ".jpg");
                Files.SaveAs(path);
                spadd.AnhDaiDien = "/Images/" + loaisp + "/" + hang + "/" + newname + ".jpg";
            }
            sp.UpdateProductByID(spadd.MaSanPham, spadd);
            return RedirectToAction("QLSanpham");
        }
        public ActionResult DeleteMulti()
        {
            SelectMulti ListItem = (SelectMulti)Session["ListSanPham"];
            if (ListItem != null)
            {
                foreach (var Item in ListItem.ListItem)
                {
                    var spdelete = db.SanPhams.Single(m => m.MaSanPham.TrimEnd() == Item.ItemID);
                    db.SanPhams.Remove(spdelete);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("QLSanPham");
        }
        public ActionResult PublishMulti()
        {
            SelectMulti ListItem = (SelectMulti)Session["ListSanPham"];
            if (ListItem != null)
            {
                foreach (var Item in ListItem.ListItem)
                {
                    var sppublish = db.SanPhams.Single(m => m.MaSanPham.TrimEnd() == Item.ItemID);
                    sppublish.Publish = true;
                    db.SaveChanges();
                }
            }
            return RedirectToAction("QLSanPham");
        }
        public ActionResult UnPublishMulti()
        {
            SelectMulti ListItem = (SelectMulti)Session["ListSanPham"];
            if (ListItem != null)
            {
                foreach (var Item in ListItem.ListItem)
                {
                    var spunpublish = db.SanPhams.Single(m => m.MaSanPham.TrimEnd() == Item.ItemID);
                    spunpublish.Publish = false;
                    db.SaveChanges();
                }
            }
            return RedirectToAction("QLSanPham");
        }
        [HttpPost]
        public JsonResult CheckItem(string ID)
        {
            SelectMulti ListItem = (SelectMulti)Session["ListSanPham"];
            if (ListItem == null)
            {
                ListItem = new SelectMulti();
            }
            Item item = new Item()
            {
                ItemID = ID,
            };
            ListItem.CheckBoxItemChage(item);
            Session["ListSanPham"] = ListItem;
            return Json(true);
        }
        #endregion
        #region[Quản lý banner]
        public ActionResult QL_Banner()
        {
            if (Session["Admin"] != null)
            {
                return View(sp.GetListBanner());
            }
            return RedirectToAction("Dang_Nhap");
        }

        public ActionResult ReversePublishBanner(int id)
        {
            sp.ReversePublishStatusOfBannerByID(id);
            return RedirectToAction("Ql_Banner");
        }
        public void DeleteBanner(int id)
        {
            sp.DeleteBannerByID(id);
        }
        #endregion
        #region Quản lí danh mục
        public ActionResult QLDanhMuc()
        {
            Session.Remove("ListDMSP");
            return View(db);
        }
        [HttpGet]
        public ActionResult SuaDM(int id)
        {
            var DMSP = db.DanhMucSanPhams.FirstOrDefault(m => m.MaDanhMuc == id);
            ViewBag.ListPublish = new SelectList(new List<bool> { true, false });
            ViewBag.ListLoaiDM = new SelectList(db.LoaiDanhMucs.ToList(), "MaLoaiDanhMuc", "TenLoaiDanhMuc");
            return View(DMSP);
        }
        [HttpPost]
        public ActionResult SuaDM(FormCollection Fc, int id)
        {
            var DMupdate = db.DanhMucSanPhams.Single(m => m.MaDanhMuc == id);
            DMupdate.TenDanhMuc = Fc["TenDanhMuc"].ToString();
            DMupdate.Publish = bool.Parse(Fc["Publish"].ToString());
            DMupdate.MaLoaiDanhMuc = int.Parse(Fc["LoaiDanhMuc"].ToString());
            db.SaveChanges();
            return RedirectToAction("QLDanhMuc");
        }

        public ActionResult DMSPUnPublishMulti()
        {
            SelectMulti ListItem = (SelectMulti)Session["ListDMSP"];
            if (ListItem != null)
            {
                foreach (var Item in ListItem.ListItem)
                {
                    int id = int.Parse(Item.ItemID);
                    var DMSPunpublish = db.DanhMucSanPhams.Single(m => m.MaDanhMuc == id);
                    DMSPunpublish.Publish = false;
                    db.SaveChanges();
                }
            }
            return RedirectToAction("QLDanhMuc");
        }

        [HttpGet]
        public ActionResult ThemDM()
        {
            ViewBag.ListPublish = new SelectList(new List<bool> { true, false });
            ViewBag.ListLoaiDanhMuc = new SelectList(db.LoaiDanhMucs.ToList(), "MaLoaiDanhMuc", "TenLoaiDanhMuc");
            return View();
        }
        [HttpPost]
        public ActionResult ThemDM(FormCollection Fc)
        {
            DanhMucSanPham dm = new DanhMucSanPham();
            dm.TenDanhMuc = Fc["TenDanhMuc"].ToString();
            dm.STT = int.Parse(Fc["STT"].ToString());
            dm.Publish = bool.Parse(Fc["Publish"].ToString());
            dm.MaLoaiDanhMuc = int.Parse(Fc["MaLoaiDanhMuc"].ToString());
            db.DanhMucSanPhams.Add(dm);
            db.SaveChanges();
            return RedirectToAction("QLDanhMuc");
        }

        public ActionResult DMSPPublishMulti()
        {
            SelectMulti ListItem = (SelectMulti)Session["ListDMSP"];
            if (ListItem != null)
            {
                foreach (var Item in ListItem.ListItem)
                {
                    int id = int.Parse(Item.ItemID);
                    var DMSPpublish = db.DanhMucSanPhams.Single(m => m.MaDanhMuc == id);
                    DMSPpublish.Publish = true;
                    db.SaveChanges();
                }
            }
            return RedirectToAction("QLDanhMuc");
        }
        public ActionResult DMSPDeleteMulti()
        {
            SelectMulti ListItem = (SelectMulti)Session["ListDMSP"];
            if (ListItem != null)
            {
                foreach (var Item in ListItem.ListItem)
                {
                    int id = int.Parse(Item.ItemID);
                    var DMSPdelete = db.DanhMucSanPhams.Single(m => m.MaDanhMuc == id);
                    db.DanhMucSanPhams.Remove(DMSPdelete);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("QLDanhMuc");
        }
        [HttpPost]
        public JsonResult DMSPCheckItem(string ID)
        {
            SelectMulti ListItem = (SelectMulti)Session["ListDMSP"];
            if (ListItem == null)
            {
                ListItem = new SelectMulti();
            }
            Item item = new Item()
            {
                ItemID = ID,
            };
            ListItem.CheckBoxItemChage(item);
            Session["ListDMSP"] = ListItem;
            return Json(true);
        }
        #endregion

        #region Quản lí người dùng
        public ActionResult QLNguoiDung()
        {
            return View(db);
        }
        [HttpGet]
        public ActionResult SuaND(string id)
        {
            var ND = db.KhachHangs.FirstOrDefault(m => m.TenDangNhap == id);
            ViewBag.ListTP = new SelectList(db.Tinh_TP.ToList(), "MaTinh_TP", "TenTinh_TP");
            return View(ND);
        }

        [HttpPost]
        public ActionResult SuaND(FormCollection Fc, string id)
        {
            var NDupdate = db.KhachHangs.Single(m => m.TenDangNhap == id);
            NDupdate.HoTen = Fc["HoTen"].ToString();
            NDupdate.TenDangNhap = Fc["TenDangNhap"].ToString();
            NDupdate.MatKhau = Fc["MatKhau"].ToString();
            NDupdate.NgaySinh = Convert.ToDateTime(Fc["NgaySinh"]);
            NDupdate.Email = Fc["Email"].ToString();
            NDupdate.SoDT = Fc["SoDT"].ToString();
            NDupdate.MaTinh_TP = int.Parse(Fc["MaTinh_TP"]);
            NDupdate.DiaChi = Fc["DiaChi"].ToString();
            NDupdate.CMT = Fc["CMT"].ToString();
            db.SaveChanges();
            return RedirectToAction("QLNguoiDung");
        }
        public ActionResult NDDeleteMulti()
        {
            SelectMulti ListItem = (SelectMulti)Session["ListND"];
            if (ListItem != null)
            {
                foreach (var Item in ListItem.ListItem)
                {
                    string id = Item.ItemID;
                    var NDdelete = db.KhachHangs.Single(m => m.TenDangNhap == id);
                    db.KhachHangs.Remove(NDdelete);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("QLNguoiDung");
        }
        [HttpPost]
        public JsonResult NDCheckItem(string ID)
        {
            SelectMulti ListItem = (SelectMulti)Session["ListND"];
            if (ListItem == null)
            {
                ListItem = new SelectMulti();
            }
            Item item = new Item()
            {
                ItemID = ID,
            };
            ListItem.CheckBoxItemChage(item);
            Session["ListND"] = ListItem;
            return Json(true);
        }
        #endregion
        #region Quản trị
        public ActionResult QuanTri()
        {
            return View(db);
        }
        [HttpGet]
        public ActionResult Sua(string id)
        {
            var QT = db.QuanTris.FirstOrDefault(m => m.TenDangNhap == id);
            ViewBag.ListTP = new SelectList(db.Tinh_TP.ToList(), "MaTinh_TP", "TenTinh_TP");
            return View(QT);
        }
        [HttpPost]
        public ActionResult Sua(FormCollection Fc, string id)
        {
            var QTupdate = db.QuanTris.Single(m => m.TenDangNhap == id);
            QTupdate.HoTen = Fc["HoTen"].ToString();
            QTupdate.TenDangNhap = Fc["TenDangNhap"].ToString();
            QTupdate.MatKhau = Fc["MatKhau"].ToString();
            QTupdate.NgaySinh = Convert.ToDateTime(Fc["NgaySinh"]);
            QTupdate.Email = Fc["Email"].ToString();
            QTupdate.SoDT = Fc["SoDT"].ToString();
            QTupdate.MaTinh_TP = int.Parse(Fc["MaTinh_TP"]);
            QTupdate.DiaChi = Fc["DiaChi"].ToString();
            QTupdate.CMT = Fc["CMT"].ToString();
            db.SaveChanges();
            return RedirectToAction("QuanTri");
        }
        public ActionResult QTDeleteMulti()
        {
           SelectMulti ListItem = (SelectMulti)Session["ListQT"];
            if (ListItem != null)
            {
                foreach (var Item in ListItem.ListItem)
                {
                    string id = Item.ItemID;
                    var QTdelete = db.QuanTris.Single(m => m.TenDangNhap == id);
                    db.QuanTris.Remove(QTdelete);
                    db.SaveChanges();
                }
            }
            return RedirectToAction("QuanTri");
        }
        [HttpPost]
        public JsonResult QTCheckItem(string ID)
        {
            SelectMulti ListItem = (SelectMulti)Session["ListQT"];
            if (ListItem == null)
            {
                ListItem = new SelectMulti();
            }
            Item item = new Item()
            {
                ItemID = ID,
            };
            ListItem.CheckBoxItemChage(item);
            Session["ListQT"] = ListItem;
            return Json(true);
        }
        #endregion
    }
}